package com.kaiwukj.android.ufamily.mvp.http.exception;

import android.net.ParseException;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;
import com.google.gson.JsonParseException;

import org.json.JSONException;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import retrofit2.HttpException;

/**
 * api异常解析类
 *
 * @author huiwings
 */
public class ExceptionHelper {

    /**
     * @param e Throwable
     * @return 错误信息(String)
     */
    public static String handleException(Throwable e) {
        String error;

        if (e == null) {
            error = "未知错误!";
        } else if (e instanceof SocketTimeoutException) {//网络超时
            LogUtils.e("网络连接超时: " + e.getMessage());
            error = "连接超时!";
        } else if (e instanceof ConnectException) { //均视为网络错误
            LogUtils.e("网络连接异常: " + e.getMessage());
            error = "网络连接异常!";
        } else if (e instanceof HttpException) {
            LogUtils.e("httpcode----->" + ((HttpException) e).code());
            if (((HttpException) e).code() >= 500) {
                error = "访问错误";
            } else {
                error = "网络错误!";
            }
        } else if (e instanceof JsonParseException
                || e instanceof JSONException
                || e instanceof ParseException) {   //均视为解析错误
            LogUtils.e("数据解析异常: " + e.getMessage());
            error = "解析失败";
        } else if (e instanceof ApiException) {//服务器返回的错误信息
            LogUtils.e("error----------->" + e.getMessage());
            error = handleMsg((ApiException) e);
        } else if (e instanceof UnknownHostException) {
            LogUtils.e("网络连接异常: " + e.getMessage());
            error = "网络连接异常!";
        } else if (e instanceof IllegalArgumentException) {
            LogUtils.e("参数异常: " + e.getMessage());
            error = "参数异常";
        } else {//未知错误
            try {
                LogUtils.e("错误: " + e.getMessage());
            } catch (Exception e1) {
                LogUtils.e("未知错误Debug调试 ");
            }
            error = "未知错误   ";
        }
        return error;
    }

    private static String handleMsg(ApiException e) {
        return StringUtils.isEmpty(handleErrCode(e.getErrCode())) ?
                e.getMessage() : handleErrCode(e.getErrCode());
    }

    public static String handleErrCode(int errCode) {
        String msg = "";
        switch (errCode) {
            /*default:
                msg = "请求失败!";
                break;*/
        }
        return msg;
    }
}
